
AddCSLuaFile( "cl_init.lua" )
AddCSLuaFile( "shared.lua" )

include('shared.lua')


AccessorFunc( ENT, "g_iType", "Type" )
AccessorFunc( ENT, "g_bFightMoving", "FightMoving" )
ENT.DeleteVotes = {}


function ENT:Initialize()

    self.Entity:PhysicsInit( SOLID_VPHYSICS ) // Make us work with physics,
    self.Entity:SetMoveType( MOVETYPE_VPHYSICS ) // after all, gmod is a physics
    self.Entity:SetSolid( SOLID_VPHYSICS )
    
    local phys = self.Entity:GetPhysicsObject()
    if (phys:IsValid()) then
        phys:Wake()
        phys:EnableMotion( false ) 
    end 
    
    self.MaxHealth = SharedBox:Health( self:GetType() )
    self.Color = team.GetColor( self:GetTeam() )
    
    self:SetFightMoving( OnDM() )
    
    if OnDM() then
    
        self:SetFWHealth( SharedBox:Health( self:GetType() ) * NicanSettings.PercentOnBuild )
        
        self:SetCollisionGroup( COLLISION_GROUP_WEAPON )
        self:SetNWBool( "b", true )
        
        self.PercentBuild = NicanSettings.PercentOnBuild
        
        self:SetFightMoving( true )
        
        if NicanSettings.BuildersPercentIsHealth == false then
            self:SetNWInt( "b%", 200 * NicanSettings.PercentOnBuild + 55 )
        end 
                
    else
    
        self.PercentBuild = 1.0    
    
        self:SetFWHealth( SharedBox:Health( self:GetType() ) )
        self:SetNWBool( "b", false )
        
        self:SpawnEffect()
    end
    
    self:FakeInit()
    self:RefreshColor()
end 


function ENT:SetFWOwner( ply )
    self:SetNWEntity( "owner" ,ply )
    
    if IsValid( ply ) && ply:IsPlayer() then
        self.OriginalOwner = ply:SteamID()
    end
    
end

function ENT:AllowMove( ply )
    return self:GetFightMoving() == true && self:FWOwner() == ply
end

function ENT:FakeCollide( data, physobj )

end

function ENT:PhysicsCollide( data, physobj )
	self:FakeCollide( data, physobj )
	
    if OnDM() then return end
    if !IsValid( data.HitEntity ) then return end
    
    //If this entity hits anotther and that entity is of another team during build mode
    //Remove it
    if data.HitEntity:IsPlayer() || IsFwBox( data.HitEntity ) then
        if data.HitEntity:Team() != self:GetTeam() then
            NicanBox:DeleteBox( self )
        end
    end
end


function ENT:OnTakeDamage(dmg)
    if OnBuild() then return end

    local TotalDmg = dmg:GetDamage() * 0.75

    if self:GetFightMoving() == true then return end
    
    //if self:IsBuilding() then TotalDmg = TotalDmg / 2 end

    local NewHealth = self:FWHealth() - TotalDmg
    
    if NewHealth <= 0 then
        NicanBox:DeleteBox( self )        
        
        return
    end

    self:SetFWHealth( NewHealth )
    self:RefreshColor()
end

//Called every 0.5seconds when a player is repairing
function ENT:Building( ply )
    
    if self:GetFightMoving() == true then
        
        if self:FWOwner() != ply then
            return
        end
    
        self:SetFightMoving( false )
    end
    
    local BoxType = self:GetType()
    
    local NewHealth = self:FWHealth() + self.MaxHealth * ((NicanSettings.BuildingRate / 2) * SharedBox:ReapirRate( BoxType ))
    if NewHealth > self.MaxHealth then 
        NewHealth = self.MaxHealth 
    end
    self:SetFWHealth( NewHealth )
    
    

    if self:IsBuilding() then
        if NicanSettings.BuildersPercentIsHealth == false then
            
            self.PercentBuild = self.PercentBuild + ((NicanSettings.BuildingRate / 2) * SharedBox:BuildingRate( BoxType ))
            
            if self.PercentBuild >= 1.0 then
                self:FinishBuild()
            else
                self:SetNWInt( "b%", 55 + 200 * self.PercentBuild )
            end
            
        else
            
            if NewHealth >= self.MaxHealth then
                self:FinishBuild()
            end
                              
        end    
    end
    
    self:RefreshColor()
end


function ENT:FinishBuild()
    self.PercentBuild = 1.0
    self:SetCollisionGroup( COLLISION_GROUP_NONE )
                
    self:SetNWBool( "b", false ) 
    self:SetNWInt( "b%", 255 )
    
    self:SpawnEffect()
end







function ENT:SetFWHealth( hp )
    self.CurHealth = hp

    self:SetNWInt("HP", hp) //Doing this because NWInt rounds off the health
end

function ENT:FWHealth()
    return self.CurHealth
end


function ENT:SpawnEffect()

    local ed = EffectData()
		ed:SetEntity( self )
	util.Effect( "propspawn", ed, true, true )
	
end


function ENT:PlayerOnTable( ply )
    for k, v in pairs( self.DeleteVotes ) do
        if v == ply then
            table.remove( self.DeleteVotes, k )
            return true
        end
    end 
    
    return false
end


function ENT:RecountVotes()
    local NumVotes = 0
    local EntTeam = self:GetTeam()
    
    for k, v in pairs( self.DeleteVotes ) do
        if IsValid( v ) && ply:Team() == EntTeam then
            NumVotes = NumVotes + 1
        else
            table.remove( self.DeleteVotes, k )
        end
    end
    
    local Owner = self:FWOwner()
    local NeededRemove = 0
    
    if IsValid( Owner ) && Owner:Team() == EntTeam then
        NeededRemove = NicanTeams:DeleteOwned( EntTeam )
    else
        NeededRemove = NicanTeams:DeleteUnOwned( EntTeam )
    end
    
    
    if NumVotes >= NeededRemove then
        NicanBox:DeleteBox( self )
    else        
        self:SetNetworkedInt("Rvotes", NumVotes)
    end
end


function ENT:NewDeleteVotes( ply )
    if ply:Team() != self:GetTeam() then return end
    
    
    if self:PlayerOnTable( ply ) == false then
        table.insert( self.DeleteVotes, ply )
    end
    
    self:RecountVotes()   
end


hook.Add("PlayerDisconnected", "RecountBoxVotes", function()
    for _, v in pairs( ents.GetAll() ) do
        if IsFwBox( v ) then
            v:RecountVotes()
        end       
    end
end )
